package org.xp.judgeplatform.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.xp.judgeplatform.common.ApiResponse;
import org.xp.judgeplatform.common.PageResult;
import org.xp.judgeplatform.pojo.dto.LoginDevices.LoginDevicesRecordDTO;
import org.xp.judgeplatform.pojo.vo.LoginDevicesVO.LoginDevicesVO;
import org.xp.judgeplatform.security.UserPrincipal;
import org.xp.judgeplatform.service.LoginDevicesService;

/**
 * 登录设备管理控制器
 *
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/loginDevices")
@CrossOrigin(origins = {"http://localhost:5173"})
@Tag(name = "登录设备管理", description = "登录设备的记录、查询和管理")
public class LoginDevicesController {

    private final LoginDevicesService loginDevicesService;

    /**
     * 记录登录设备
     */
    @PostMapping("/record")
    @Operation(
            summary = "记录登录设备",
            description = "用户登录时记录设备信息",
            security = @SecurityRequirement(name = "bearerAuth")
    )
    public ApiResponse<LoginDevicesVO> recordLoginDevice(
            @Parameter(description = "登录设备记录信息", required = true)
            @Valid @RequestBody LoginDevicesRecordDTO recordDTO,
            Authentication authentication) {
        log.info("收到登录设备记录请求: {}", recordDTO);

        // 从认证信息中获取当前用户ID
        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        Integer userId = principal.getId();

        recordDTO.setUserId(userId);

        LoginDevicesVO loginDevicesVO = loginDevicesService.recordLoginDevice(recordDTO);

        return ApiResponse.success(loginDevicesVO);
    }

    /**
     * 获取用户的登录设备列表（分页）
     */
    @GetMapping("/{userId}")
    @Operation(
            summary = "获取登录设备列表",
            description = "分页查询用户的登录设备记录",
            security = @SecurityRequirement(name = "bearerAuth")
    )
    public ApiResponse<PageResult<LoginDevicesVO>> getUserDevices(
            @Parameter(description = "用户ID", required = true)
            @PathVariable Integer userId,
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(defaultValue = "10") Integer pageSize,
            Authentication authentication) {
        log.info("获取用户登录设备列表，userId: {}, pageNum: {}, pageSize: {}", userId, pageNum, pageSize);

        UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
        if (!principal.getId().equals(userId)) {
            return ApiResponse.error(403, "无权访问其他用户的设备信息");
        }

        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }

        PageResult<LoginDevicesVO> result = loginDevicesService.getUserDevices(userId, pageNum, pageSize);

        return ApiResponse.success(result);
    }

    // TODO: 其他接口方法待实现
    // - GET /{userId}/current - 获取当前设备
    // - POST /{userId}/logout/{deviceId} - 登出指定设备
    // - POST /{userId}/logoutAll - 登出所有其他设备
    // - DELETE /{userId}/{deviceId} - 删除设备记录
    // - PUT /{userId}/{deviceId}/name - 更新设备名称
}
